﻿using TrueSync;
using UnityEngine;

namespace HEFramework
{
    public static class MoveComponentSystem
    {
        [EntitySystem]
        public class MoveComponentAwakeSystem : AwakeSystem<MoveComponent>
        {
            protected override void Awake(MoveComponent _self)
            {
            }
        }


        [EntitySystem]
        public class MoveComponentUpdateSystem : UpdateSystem<MoveComponent>
        {
            protected override void Update(MoveComponent _self)
            {
                _self.Move();
            }
        }

        public static void SetTarget(this MoveComponent _self, TSVector _pA, TSVector _pB, FP _speed)
        {
            _self.APos = _pA;
            _self.BPos = _pB;
            _self.Speed = _speed;
        }

        public static void SetTarget(this MoveComponent _self, TSVector _pB)
        {
            var tc = _self.GetParentChild<TransformComponent>();
            var ac = _self.GetParentChild<AttributeComponent>();
            if (tc == null || ac == null)
            {
                return;
            }

            _self.APos = tc.P;
            _self.BPos = _pB;
            _self.Speed = ac.MV_SP.Value;
        }

        private static void Move(this MoveComponent _self)
        {
            var tc = _self.GetParentChild<TransformComponent>();
            if (tc == null || _self.APos == _self.BPos)
            {
                return;
            }

            //不允许靠太近
            FP dis = TSVector.Distance(_self.APos, _self.BPos);
            if (dis < 0.01)
            {
                _self.APos = _self.BPos;
                return;
            }

            TSVector dir = TSVector.zero;
            //尝试移动
            dir = ((_self.BPos - _self.APos).normalized * Formula.LG(_self.Speed) * Time.deltaTime);
            _self.APos += dir;
            tc.P = _self.APos;
        }
    }
}